package com.supinfo.food.dao.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;

import com.supinfo.food.dao.CustomerDao;
import com.supinfo.food.entities.Customer;
import com.supinfo.food.entities.User;

/**
 * Customer DAO
 * 
 * @author Syn
 */
public class JpaCustomerDao implements CustomerDao {

	/** Entity manager */
	private EntityManager entityManager;

	public JpaCustomerDao() {
		entityManager = ManagerDAO.getEntityManager();
	}

	@Override
	public Customer addCustomer(Customer customer) {
		entityManager.getTransaction().begin();
		entityManager.persist(customer);
		entityManager.getTransaction().commit();
		return customer;
	}

	@Override
	public Customer findCustomer(Long id) {
		try {
			return entityManager.find(Customer.class, id);
		} catch (NoResultException e) {
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Customer> getAllCustomers() {
		return entityManager.createQuery("SELECT d FROM Customer d")
				.getResultList();
	}

	@Override
	public Customer updateCustomer(Customer customer) {
		entityManager.getTransaction().begin();
		entityManager.merge(customer);
		entityManager.getTransaction().commit();
		return customer;
	}

	@Override
	public void removeCustomer(Customer customer) {
		entityManager.getTransaction().begin();
		entityManager.remove(customer);
		entityManager.getTransaction().commit();
	}

	@Override
	public void removeCustomer(Long id) {
		Customer customer = findCustomer(id);
		if (customer != null) {
			entityManager.getTransaction().begin();
			entityManager.remove(customer);
			entityManager.getTransaction().commit();
		}
	}

}
